package com.chen.test;

import java.io.IOException;

import org.markdown4j.Markdown4jProcessor;

import com.chen.sql.Question;

import gen.R;
import gui.Activity;
import gui.framework.intent.Bundle;
import gui.framework.intent.Intent;
import gui.sql.DBHelper;
import gui.view.Button;
import gui.view.EditText;
import gui.view.EditText.OnTextChangedListener;
import gui.view.View;
import gui.view.View.OnClickListener;
import gui.view.WebView;

public class AddActivity extends Activity {
	private EditText webedit;
	private WebView webview;
	private Button save;
	private EditText titleEdit;
	private Markdown4jProcessor process;
	private boolean edit;
	private Question question;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_activity);
		init();
		findView();
		addListener();
		Intent i = getIntent();
		if (edit = (i != null)) {
			question = (Question) i.getExtra().getSerializable("question");
			titleEdit.setText(question.getTitle());
			webedit.setText(question.getContext());
			try {
				String html = process.process(question.getContext());
				webview.setText(html);
			} catch (IOException e) {
			}
		}
	}

	private void init() {
		process = new Markdown4jProcessor();
	}

	private void addListener() {
		webedit.setOnTextChangedListener(new OnTextChangedListener() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				try {
					String html = process.process(s.toString());
					webview.setText(html);
				} catch (IOException e) {
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(EditText s) {
			}
		});
		save.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				save();
			}
		});
	}

	protected void save() {
		if (edit) {
			DBHelper.update("update question set title=?,create_time=?,context=?,export=? where id=?",
					titleEdit.getText(), System.currentTimeMillis(), webedit.getText(), 0, question.getId());
		} else {
			DBHelper.insert("insert into question (title,create_time,lookcounter,context) values (?,?,?,?)",
					titleEdit.getText(), System.currentTimeMillis(), 0, webedit.getText());
		}
		titleEdit.setText("");
		webedit.setText("");
		webview.setText("");
		onFinish();
	}

	private void findView() {
		webedit = (EditText) findViewById(R.id.webedit);
		webview = (WebView) findViewById(R.id.webview);
		save = (Button) findViewById(R.id.save_add_activity);
		titleEdit = (EditText) findViewById(R.id.title_add_activity);
	}

	@Override
	protected void onDestory() {
		startActivity(MainActivity.class);
	}
}
